package zhy.UseViewGroupCustomPullHeader;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class ViewGroupPull extends ViewGroup {

	Button first;
	int firstHeight;
	GestureDetector detector;
	
	public ViewGroupPull(Context context) {
		super(context);
		init(context);
	}
	public ViewGroupPull(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}
	
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		for(int i=0;i<getChildCount();i++)
		{
			getChildAt(i).measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
			//getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
		}
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int topNow=0;
		for(int i=0;i<getChildCount();i++)
		{
			View child=getChildAt(i);
			int width=child.getMeasuredWidth();
			int height=child.getMeasuredHeight();
			if(i==0)
			{
				firstHeight=height;
				//System.out.println(getScrollY());
				scrollTo(0, firstHeight);
				//System.out.println(getScrollY());
			}
			child.layout(0, topNow, width, topNow+height);
			topNow+=height;
			
		}

	}
	
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		return detector.onTouchEvent(ev);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		detector.onTouchEvent(event);
		if(MotionEvent.ACTION_UP==event.getAction())
		{
			scrollTo(0, firstHeight);
		}
		return true;
	}
	
	void init(Context context)
	{
		first=new Button(context);
		first.setText("aa");
		addView(first);
		
		detector=new GestureDetector(context, new OnGestureListener(){

			@Override
			public boolean onDown(MotionEvent e) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void onShowPress(MotionEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public boolean onSingleTapUp(MotionEvent e) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean onScroll(MotionEvent e1, MotionEvent e2,
					float distanceX, float distanceY) {
				// TODO Auto-generated method stub
				//return false;
				
				scrollBy(0, (int)distanceY);
				return true;
			}

			@Override
			public void onLongPress(MotionEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2,
					float velocityX, float velocityY) {
				// TODO Auto-generated method stub
				return false;
			}});
	}

}
